package sampledb

import sweet.helper._
import sweet.helper.jdbc._
import sweet.helper.mail._
import sweet.mvc.api._

class SampleDbSweetConfig extends SweetConfig {
  loadSysProps("sample-db.config", "classpath:/config.properties")
  
  addLayouts("main"->"/view/layout/main.ftl")
  
  val adminEmail = props("admin.email")
  val emailSender = new EmailSender(
    props("mail.host"), props("mail.smtp.port").toInt, props("mail.from"), 
    props("mail.smtp.auth").toBoolean, props("mail.user"), props("mail.password"))
    
  val dataSource = JdbcHelper(props("db.user"), props("db.password"), props("db.url"), props("db.driver")).dataSource
  val userDao = new UserDao(dataSource)
  val feedbackDao = new FeedbackDao(dataSource)
    
  def setupConfig {
    // toolbox.auto.update.begin << DO NOT REMOVE IF YOU WANT Toolbox to auto- generate files
    addControllers("/feedback" -> new FeedbackController(adminEmail, emailSender, feedbackDao))
    addControllers("/user" -> new UserController(emailSender, userDao, props("loginUrl"), adminEmail, props("siteUrl")))
    addControllers("/main" -> new MainController)      
    // toolbox.auto.update.end
    
    
    //Get appVersion for this webapp and save it.
    val appVersion = getAppVersion(servletContextRealPath)
    logger.debug("Setting appVersion to " + appVersion)
    addProps("appVersion" -> appVersion)
    servletContext.setAttribute("appVersion", appVersion)
    
    addInterceptorWithExceptList(new UserLoginInterceptor, "/user", List("/login-form", "/new-form")) 
  }
  
  /** Get user application version string. */
  def getAppVersion(ctxPath: String) = {
    val attr = sweet.helper.ManifestHelper.manifestAttributes(ctxPath)
    //logger.debug("Manifest as props " + (Map() ++ attr).toString)
    attr.getOrElse("Implementation-Name", "sample-db-development.latest")
  }
}

